<template>
	<view class="container">
		<!-- 基本信息 -->
		<view class="foundation">基本信息</view>
		<!-- 入库信息 -->
		<view class="ation">
			<view class="block">
				<view>关联采购订单</view>
				<view style="color: #999999;">{{list.no}}</view>
			</view>
			<!-- <view class="block">
				<view>供应商</view>
				<view style="color: #999999;">{{list.supplierName?list.supplierName:'暂无'}}</view>
			</view> -->
			<view class="block">
				<view>入库类型</view>
				<view style="color: #999999;">采购入库</view>
			</view>
			<!-- <view class="block">
				<view>存储仓库</view>
				<view style="color: #999999;">总仓</view>
			</view> -->
			<!-- <view class="block">
				<view>货品种类</view>
				<view style="color: #999999;">5 (已入库3，部分入库1，待入库1)</view>
			</view> -->
			<view class="block" @click="show = true">
				<view>结算账户</view>
				<view style="color: #999999;">{{list.accountName||'暂无'}}</view>
			</view>
			<view class="block" style="border-bottom: 1rpx solid #ffffff;">
				<view>采购日期</view>
				<view style="color: #999999;">{{list.createTime?setTimes(list.createTime) : ''}}</view>
			</view>
		</view>
		<!-- 实际入库货品 -->
		<view class="foundation">
			<span>实际入库货品(共</span>
			<span style="color: #177A77 ;text-decoration: underline;">{{sourceArray.length || 0}}</span>
			<span>个种类)</span>
		</view>
		<!-- 入库商品 -->
		<view class="storeGoods">
			<view class="goods" v-for="(item,index) in list.items" :key="index" @click="handeleDetail(item,index)">
				<view class="name">{{item.productName}}</view>
				<view class="sum">数量：{{item.count}}</view>
				<view class="sum">单位：{{item.productUnitName}}</view>
				<view class="operate1" v-if="item.inCount==0">待入库</view>
				<view class="operate2" v-else-if="item.inCount<item.count">部分入库</view>
				<view class="operate2" v-else="item.inCount>=item.count">入库完成</view>
				<!-- <view class="operate3" >已入库></view> -->
				<!-- 删除图标 -->
				<view class="removeblock" v-if="!(item.inCount==item.count)" @click.stop="handeleRemove(index,item.id)">
					<image class="remove" src="/static/work/sc_del.png" mode=""></image>
				</view>
			</view>
		</view>

		<!-- <view class="expand" @click="insertData" v-if="isMore&&sourceArray.length>3">
			<span>展开（货品）</span>
			<span>
				<image style="width: 20rpx;height: 17rpx;" src="/static/work/ty_down_arrow.png" mode=""></image>
			</span>
		</view>
		<view class="expand" v-else-if="!isMore&&sourceArray.length>3" @click="handeleRetract">收起</view> -->
		
		<view class="submit">
			<u-button :loading="loading" :custom-style="customStyleBtn1" @click="toImprove">提交入库单</u-button>
		</view>
		
		<u-picker :show="show" :columns="Account" keyName="name" @cancel="show=false" @confirm="handleConfirm"></u-picker>
	</view>
</template>
<script>
	import {getPurchaseOrder,createPurchase,settlementAccount}  from '@/api/store.js'
	import {setTimes} from '@/utils/common.js'
	export default {
		data() {
			return {
				show:false,
				list:{},//详情页数据
				isMore:true,
				sourceArray: [], //原数组
				targetArray: [], // 目标数组
				currentIndex: 3, // 当前插入的位置
				title: 'Hello',
				customStyleBtn1: {
					width: '690rpx',
					height: '90rpx',
					borderRadius: '45rpx',
					background: "linear-gradient(0deg, #177A77, #4B9C6D)",
					fontSize: '28rpx',
					fontWeight: 400,
					color: '#ffffff',
					border: 'none',
					lineHight:'50rpx !important'
				},
				loading:false,
				id:'',
				Account:[],//结算账户列表
			}
		},
		onLoad(option) {
			
			console.log('option:',JSON.parse(option.items));
			this.list = JSON.parse(option.items)
			this.list.items = this.list.items.filter(item=>item.inCount<item.count)
			this.sourceArray.push(...JSON.parse(option.items).items.filter(item=>item.inCount<item.count))
			this.targetArray = JSON.parse(option.items).items.filter(item=>item.inCount<item.count).slice(0,3)
			
			this.handleCustomEventBind = this.handleCustomEvent.bind(this);
			uni.$on('store', this.handleCustomEventBind);
			this.getAccount() //获取结算账户
		},
		methods: {
			// 提交数据
			async toImprove(){
				if(!this.list.accountId){
					uni.showToast({
						title:'请选择结算账户',
						icon:'none',
						duration:4000
					})
					return
				}
				for(const item of this.list.items){
					if(!item.isStorage){
						uni.showToast({
							title:'商品'+item.productName+'的货位为空，请选择货位或删除项目',
							icon:'none',
							duration:4000
						})
						bol = true
						break; // 找到目标，终止循环
					}
					if(!item.count){
						uni.showToast({
							title:'商品'+item.productName+'的货位为空，请输入数量或删除项目',
							icon:'none',
							duration:4000
						})
						bol = true
						break; // 找到目标，终止循环
					}
				}
				
				this.loading = true
				this.list.inTime = Math.floor(Date.now() / 1000)*1000
				this.list.items = this.list.items.map(item=>{
					return{
						...item,
						orderItemId:item.id
					}
				})
				this.list.orderId=this.id
				let obj = {
					accountId:this.list.accountId,//结算账户
					discountPercent:this.list.discountPercent,
					discountPrice: this.list.discountPrice,
					fileUrl: this.list.fileUrl,
					inTime: this.list.createTime,
					orderId:this.list.id,
					orderNo: this.list.no,
					otherPrice: '',
					remark:this.list.remark,
					supplierId:this.list.supplierId,
					totalPrice: this.list.totalPrice,
					items:[]
				}
				let items = this.list.items.map(item=>{
						return item.warehouseList.map(v =>({
							arrivalPrice:item.arrivalPrice,
							arrivalTotalPrice:item.arrivalTotalPrice,
							batchNumber:item.batchNumber,
							count:v.count,
							piece:item.piece,
							productSpecificationName:item.productSpecificationName,//规格
							grossWeight:item.grossWeight,//毛重
							tareWeight:item.tareWeight,//皮重
							netWeight:item.netWeight,//净重
							quantity:item.quantity,//件数
							highWarning:item.highWarning,//最高预警数量
							lowWarning:item.lowWarning,//最低预警数量
							freeOrNot:item.freeOrNot,
							giftCount:item.giftCount,
							inCount:item.inCount,
							orderItemId:item.id,
							productBarCode:item.productBarCode,
							productId:item.productId,
							productName:item.productName,
							productPrice:item.productPrice,
							productUnitId:item.productUnitId,
							productUnitName:item.productUnitName,
							purchaseCount:item.purchaseCount,
							productType:item.productType,
							producedDate:item.producedDate,
							samplingRate:item.samplingRate,
							qcRemark:item.qcRemark,
							qcState:item.qcState,
							remark:item.remark,
							returnCount:item.returnCount,
							stockCount:item.stockCount,
							taxPercent:item.taxPercent,
							totalCount:item.count,
							totalPrice:(
							  Array.isArray(item.warehouseList) && item.warehouseList.length > 0 
							    ? item.warehouseList.reduce((acc, curr) => acc + (curr.count || 0), 0) * item.arrivalPrice 
							    : 0
							),
							totalProductPrice: (
							  Array.isArray(item.warehouseList) && item.warehouseList.length > 0 
							    ? item.warehouseList.reduce((acc, curr) => acc + (curr.count || 0), 0) * item.arrivalPrice 
							    : 0
							),
							taxPrice:item.taxPrice,
							warehouseId:v.warehouseId,
							warehouseList:item.warehouseList
						}))
					
					}).flat()
					let objs = JSON.parse(JSON.stringify(obj))
					objs.items =items
				try{
					let res = await createPurchase(objs)
					uni.navigateBack()
					uni.$emit('getList')
					uni.showToast({
						title:'操作成功',
						icon:'none'
					})
					this.loading = false
				} catch (error){
					this.loading = false
				}
			},
			// 获取结算账户信息
			async getAccount(){
				let res = await settlementAccount()
				let data = res.data
				let arr = data.filter(item=>item.id==this.list.accountId)
				if(arr.length>0){
					this.list.accountName = arr[0].name
				}
				this.Account.push(res.data) 
			},
			// 获取数据
			async getData(id) {
				let response = await getPurchaseOrder({productId:id})
				console.log('response:',response);
				// this.list = response.data
				// this.sourceArray.push(...response.data.items)
				// this.targetArray = response.data.items.slice(0,3)
			},
			// 删除
			handeleRemove(index,id) {
				uni.showModal({
					title: '提示',
					content: '确认删除此条信息？',
					success: res => {
						if (res.confirm) {
							this.targetArray.splice(index, 1)
							let i = this.sourceArray.findIndex(item=>item.id==id)
							this.sourceArray.splice(i,1)
							this.currentIndex = this.currentIndex-1
							if(this.targetArray.length==0 ){
								this.insertData()
							}
							let y = this.list.items.findIndex(item=>item.id==id)
							this.list.items.splice(y,1)
						}
					}
				});
			},
			// 页面跳转传参
			handeleDetail(item, index) {
				if(item.inCount==0 || item.inCount<item.count){
					uni.navigateTo({
						url: '/pages/work/store/purchase?item='+JSON.stringify(this.list.items[index])+'&index='+index
					})
				}
			},
			// 选择结算账户
			handleConfirm(val){
				this.list.accountId = val.value[0].id
				this.list.accountName = val.value[0].name
				this.show = false
			},
			// 收起
			handeleRetract(){
				this.currentIndex =3
				this.targetArray = this.sourceArray.slice(0,3)
				this.currentIndex=3
				this.isMore = true
			},
			// 时间戳转换
			setTimes(times){
				return setTimes(times)
			},
			// 添加数据
			insertData() {
				// 如果还有数据可以插入
				if (this.currentIndex < this.sourceArray.length) {
					// 从当前索引开始取出 5 条数据
					let index1 = Number(this.sourceArray.length)
					let index2 = Number(this.currentIndex+5)
					// 如果索引的值大于总原数组长度
					if(index2>index1){
						// 二次截取的时候  截取初始索引至索引值减去大于的长度
						const dataToInsert = this.sourceArray.slice(this.currentIndex, this.currentIndex + (5-(index2-index1)));
						this.targetArray.push(...dataToInsert);
						this.isMore = false
					}else{
						const dataToInsert = this.sourceArray.slice(this.currentIndex, this.currentIndex + 5);
						this.targetArray.push(...dataToInsert);
					}
					// 更新当前索引
					this.currentIndex += 5;
				} 
			},
			// 上个页面传参
			handleCustomEvent(val){
				// 更新对象对应数组下标的数据
				// this.$set(this.list.items, val.data.index, {...this.list.items[val.data.index], ...val.data.items});
				let data = JSON.parse(JSON.stringify(this.list))
				data.items[val.data.index] = val.data.items
				this.list.items=data.items
			}
		}
	}
</script>

<style scoped>
	.submit{
		width: 100%;
		height: 150rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.expand {
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 24rpx;
		color: #999999;
	}

	.removeblock {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.operate1 {
		margin-right: 30rpx;
		color: #FBA349 ;
	}
	.operate2 {
		margin-right: 30rpx;
	}
	.operate3 {
		margin-right: 30rpx;
		color: #999999;
	}

	.sum {
		margin-right: 35rpx;
	}

	.name {
		width: 150rpx;
		white-space: nowrap;
		/* 禁止文本换行 */
		overflow: hidden;
		/* 隐藏超出范围的内容 */
		text-overflow: ellipsis;
		/* 使用省略号 */
		margin-right: 40rpx;
	}

	.storeGoods {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #FFFFFF;
		font-size: 24rpx;
	}

	.goods {
		width: 688rpx;
		height: 104rpx;
		display: flex;
		align-items: center;
		border-bottom: 1rpx solid #EEEEEE;
	}
	.goods-active{
		width: 688rpx;
		height: 104rpx;
		display: flex;
		align-items: center;
	}

	.remove {
		width: 22rpx;
		height: 24rpx;
	}

	.block {
		width: 688rpx;
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #EEEEEE;
		font-size: 24rpx;
	}

	.foundation {
		width: 100%;
		height: 60rpx;
		display: flex;
		align-items: center;
		padding: 0 0 0 38rpx;
		box-sizing: border-box;
		font-weight: 400;
		font-size: 24rpx;
		color: #333333;
	}

	.ation {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #FFFFFF;
	}

	.container {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #F8F8F8;
	}

	page {
		background-color: #F8F8F8;
	}
</style>